package io.renren.modules.mark.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.renren.common.exception.RRException;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.mark.entity.MarkDatasetEntity;
import io.renren.modules.mark.entity.MarkTeamEntity;
import io.renren.modules.mark.entity.MarkTeamUserEntity;
import io.renren.modules.mark.form.TeamUser;
import io.renren.modules.mark.service.MarkDatasetService;
import io.renren.modules.mark.service.MarkTeamService;
import io.renren.modules.mark.service.MarkTeamUserService;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.*;



/**
 * 
 *
 * @author 
 * @email 
 * @date
 */
@RestController
@RequestMapping("mark/markteam")
@Api(value = "TeamApi", description = "团队增删改查",  tags = {"团队接口"})
public class MarkTeamController extends AbstractController {
    @Autowired
    private MarkTeamService markTeamService;
    @Autowired
    private MarkTeamUserService markTeamUserService;
    @Autowired
    private SysUserService sysUserEntity;
    @Autowired
    private MarkDatasetService markDatasetService;


    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("mark:markteam:list")
    public R list(@RequestParam  Map<String, Object> params){
        Long userId = getUserId();
        if(userId!= Constant.SUPER_ADMIN && userId!= Constant.ADMIN){
            params.put("createUserid",userId);
        }
        PageUtils page = markTeamService.queryPage(params);

        return R.ok().put("page", page);
    }

    @GetMapping("/listTeam")
    public R listTeam(){
        QueryWrapper<MarkTeamEntity> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        Long userId = getUserId();
        if(userId!= Constant.SUPER_ADMIN && userId!= Constant.ADMIN){
            wrapper.eq("create_userid",getUserId());
        }
        wrapper.eq("is_delete",0);
        List<MarkTeamEntity> list = markTeamService.list(wrapper);
        return R.ok().put("list", list);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{teamId}")
    //@RequestMapping("/info/{teamId}")
    //@RequiresPermissions("mark:markteam:info")
    @ApiOperation("团队信息")
    public R info(@PathVariable("teamId") Integer teamId){
		MarkTeamEntity markTeam = markTeamService.getById(teamId);

        //finish 根据teamId查询出team信息以及对应的标注成员信息
        QueryWrapper<MarkTeamUserEntity> mtu = new QueryWrapper<MarkTeamUserEntity>();
        mtu.eq("team_id", teamId);
        List<MarkTeamUserEntity> uids = markTeamUserService.list(mtu);

        List<Integer> suids = new ArrayList<Integer>();
        //suids.add(-1);
        for(MarkTeamUserEntity x :uids) {
            suids.add(x.getUserId());
        }
        if(suids.size() == 0){
            return R.ok().put("markTeam", markTeam).put("users",suids);
        }
        QueryWrapper<SysUserEntity> user = new QueryWrapper<SysUserEntity>();
        user.in("user_id", suids);

        List<SysUserEntity> u_info = sysUserEntity.list(user);

        return R.ok().put("markTeam", markTeam).put("users", u_info);
        //return R.ok().put("markTeam", markTeam);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @RequiresPermissions("mark:markteam:save")
    @ApiOperation("团队保存")
    public R save(@RequestBody TeamUser form){
        MarkTeamEntity mt = new MarkTeamEntity();
        mt.setName(form.getName());
        mt.setTeamDesc(form.getTeamDesc());
        mt.setCreateTime(new Date());
        mt.setIsDelete(0);
        mt.setCreateUserid(getUserId());
        try{
            markTeamService.save(mt);
        }catch (Exception dk){
            if(dk.getMessage().contains("mark_team.name_UNIQUE")){
                throw new RRException("团队名称已存在");
            }else {
                throw new RRException("保存团队失败,请检查团队名称是否过长");
            }
        }

        List<Integer> A = form.getUserId();
        if(A.size() == 0)
            return R.ok();

        //insert
        List<MarkTeamUserEntity> i_mtu = new ArrayList<MarkTeamUserEntity>();
        for(Integer x : A){
            MarkTeamUserEntity i = new MarkTeamUserEntity();
            i.setTeamId(mt.getTeamId());
            i.setUserId(x);
            i_mtu.add(i);
        }
        markTeamUserService.saveBatch(i_mtu);
        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation("团队更新")
    public R update(@RequestBody TeamUser form){
        //查询团队下是否有任务在进行中
        QueryWrapper<MarkDatasetEntity> qw = new QueryWrapper<>();
        qw.eq("team_id",form.getTeamId()).eq("state",1);
        List<MarkDatasetEntity> list = markDatasetService.list(qw);
        if (list.size() > 0){ //有任务在进行中
            throw new RRException("该团队下有正在进行中的任务，不能进行人员变更");
        }

        //finish 团队更新，包括团队信息以及成员增加删除动作
        MarkTeamEntity mt = new MarkTeamEntity();
        if(form.getTeamId() == null){
            return R.error("团队ID为空");
        }
        mt.setTeamId(form.getTeamId());
        mt.setName(form.getName());
        mt.setTeamDesc(form.getTeamDesc());
        try{
            markTeamService.updateById(mt);
        }catch (Exception dk){
            if(dk.getMessage().contains("mark_team.name_UNIQUE")){
                throw new RRException("团队名称已存在");
            }else {
                throw new RRException("更新团队失败,请检查团队名称是否过长");
            }
        }

        List<Integer> insert = new ArrayList<Integer>();
        List<Integer> A = form.getUserId();
        for(Integer x :A){
            insert.add(x);
        }

        QueryWrapper<MarkTeamUserEntity> mtu = new QueryWrapper<MarkTeamUserEntity>();
        mtu.eq("team_id", form.getTeamId());
        List<MarkTeamUserEntity> uids = markTeamUserService.list(mtu);

        List<Integer> B = new ArrayList<Integer>();
        for(MarkTeamUserEntity x :uids) {
            B.add(x.getUserId());
        }
        insert.removeAll(B);
        B.removeAll(A);

        //delete
        if(B.size() != 0) {
            QueryWrapper<MarkTeamUserEntity> mte = new QueryWrapper<MarkTeamUserEntity>();
            mte.eq("team_id", form.getTeamId()).in("user_id", B);
            markTeamUserService.remove(mte);
        }
        //insert
        List<MarkTeamUserEntity> i_mtu = new ArrayList<MarkTeamUserEntity>();
        for(Integer x : insert){
            MarkTeamUserEntity i = new MarkTeamUserEntity();
            i.setTeamId(form.getTeamId());
            i.setUserId(x);
            i_mtu.add(i);
        }
        markTeamUserService.saveBatch(i_mtu);
        return R.ok();
    }

    /**
     * 删除团队，将团队的is_delete值置为-1即可
     * @param teamIds
     * @return
     */
	@PostMapping("/delete")
    @ApiOperation("删除团队")
    public R delete(@RequestBody @ApiParam(name="团队ID", value="团队ID的列表", required=true) Integer[] teamIds){
        ArrayList<String> teamNameList = new ArrayList<>();
        for (Integer teamId : teamIds) {
            //查询团队下是否有任务在进行中
            QueryWrapper<MarkDatasetEntity> qw = new QueryWrapper<>();
            qw.eq("team_id",teamId).eq("state",1);
            List<MarkDatasetEntity> list = markDatasetService.list(qw);
            if (list.size() > 0){ //有任务在进行中
                MarkTeamEntity teamEntity = markTeamService.getById(teamId);
                teamNameList.add(teamEntity.getName());
                continue;
            }
            markTeamService.update(new UpdateWrapper<MarkTeamEntity>().set("is_delete",-1).eq("team_id",teamId));
            markTeamUserService.update(new UpdateWrapper<MarkTeamUserEntity>().set("is_delete",-1).eq("team_id",teamId));
        }
        if(teamNameList.size() >0){
            String teamNames = teamNameList.stream().reduce((a, b) -> a + "," + b).get();
            throw new RRException("以下团队有任务在进行中，删除失败，团队名："+teamNames);
        }

        // throw new RRException("团队名："+teamEntity.getName()+"，下有任务在进行中，不能删除");

        // markTeamService.removeByIds(Arrays.asList(teamIds));

        //finish 根据teamIds 删除团队和用户多对多表中的信息
        // for(Integer x :teamIds){
        //     Map<String, Object> columnMap = new HashMap<>();
        //     columnMap.put("team_id", x);
        //     markTeamUserService.removeByMap(columnMap);
        // }
        return R.ok();
    }

}
